package feifei.second;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/userInfo.action")
public class UserServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");
        String username = req.getParameter("username");
        String dateOfBirth = req.getParameter("dateOfBirth");
        String hobbies = req.getParameter("hobbies");
        String birthCity = req.getParameter("birthCity");
        String gender = req.getParameter("gender");
        //JavaBean 把获取的表单数据封装到对象中
        User user = new User(username, dateOfBirth, hobbies, birthCity, gender);
//        HttpSession session = req.getSession();//第二道作业
//        session.setAttribute("user", user);//第二道作业
//        resp.sendRedirect(req.getContextPath()+"/homework/userInfo1.jsp");//第二道作业

        HttpSession session = req.getSession();
//        ServletContext context = this.getServletContext();
        List<User> userList = (List<User>) session.getAttribute("user");
        if (userList == null) {
            userList = new ArrayList<>();

        }
        //userList此时不为空,不做去重
        userList.add(user);
        session.setAttribute("user", userList);
        //资源跳转
        resp.sendRedirect(req.getContextPath()+"/homework/addUser.jsp");
    }

}
